//
//  FPMainViewController.m
//  FilmParadise
//  tag --- 100----103  105 -----107  110 - 113
//  Created by lanou3g on 15/7/13.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>
#import "FPMainViewController.h"
#import "FPMainTopTableViewCell.h"
#import "FPVisualEffectView.h"
#import "FPThreeBtnTableViewCell.h"
#import "FPFootView.h"
#import "FPTodayHotTableViewCell.h"
#import "FPThreeImageTableViewCell.h"
#import "FPTodayHotView.h"
#import "FPEveryMovieHeadView.h"
#import "FPGoodMovieTableViewCell.h"
#import "FPLocation.h"
#import "FPNetUrl.h"
#import "FPNetWork.h"
#import "FPmainTopViewModel.h"
#import "FPFindCinemaModel.h"
#import "FPTodayHotModel.h"
//#import "LORequestManger.h"
#import "FPTodayMovieModel.h"

#import "FPRootViewController.h"
#import "FPMovieViewController.h"
#import "FPCinemaViewController.h"

#import "FPNewsViewController.h"
#import "FPPrevueViewController.h"
#import "FPTopViewController.h"
#import "FPMovieDetailViewController.h"
#import "FPCommWebView.h"
#import "FPWebViewController.h"
#import "FPFilmcriticViewController.h"
#import <CoreLocation/CoreLocation.h>
#define kmainTopUrl @"http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=%@"
#define kTodayHot @"http://api.m.mtime.cn/PageSubArea/GetFirstPageAdvAndNews.api"
#define kLocation @"http://api.m.mtime.cn/GetCityByLongitudelatitude.api?latitude=%f&longitude=%f"
@interface FPMainViewController ()<UITableViewDelegate, UITableViewDataSource, iCarouselDelegate, iCarouselDataSource, CLLocationManagerDelegate, AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIView *returnView;
@property (nonatomic, strong) UIImageView *imageQR;
//@property (nonatomic, strong)iCarousel *icarousel;

@property (nonatomic, strong) CLLocationManager *LocMan;

@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) MBProgressHUD *HUD2;
@property (nonatomic, strong) NSMutableDictionary *imageDic;
@property (nonatomic) NSInteger imageIndex;
@property (nonatomic, strong) UIView *statusBarView;
@property (nonatomic, strong) NSMutableArray *topModelArr;
@property (nonatomic, strong) NSMutableArray *topImageArr;

@property (nonatomic, strong) NSMutableArray *todayHotModelArr;
@property (nonatomic, strong) NSMutableArray *todayMovieArr;
@property (nonatomic, strong) FPFindCinemaModel *FindCinemaModel;
@property (nonatomic, strong) FPTodayMovieModel *todayMovieModel;

@property (nonatomic, strong) UIBarButtonItem *locationBtn;
@property (nonatomic)BOOL isLocation;
@property (nonatomic)BOOL isScanf;

@property (nonatomic, strong) UILabel *captureLabel;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, strong) CAShapeLayer *overlay;
@property (nonatomic)BOOL isFlashLight;
@property (nonatomic, strong)UIView *QRLine;

@property (nonatomic, strong)UIWebView *webView;
@end

@implementation FPMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(@"DDDDD%ldHHHHHH%ldMMMMMMM%ld",[self setDay],[self setHour],[self setMinute]);
    self.navigationController.navigationBar.translucent = YES;
    [self setNavigationView];
    [self setUrl];
    self.LocMan.delegate = self;
    
    [self setLocation];
//    self.icarousel.dataSource = self;
//    self.icarousel.delegate = self;
    self.tableView.bounces = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    
//    self.tableView.backgroundColor = [UIColor redColor];
    
    


}



- (NSInteger)setHour
{
    NSDate *now=[NSDate date];
    NSCalendar *cal=[NSCalendar currentCalendar];
    unsigned int time=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    NSDateComponents *t=[cal components:time fromDate:now];
    
    int hour=(int)[t hour];
    NSLog(@"%d",hour);
    return (NSInteger)hour;
}

- (NSInteger)setDay
{
    NSDate *now=[NSDate date];
    NSCalendar *cal=[NSCalendar currentCalendar];
    unsigned int time=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    NSDateComponents *t=[cal components:time fromDate:now];
    
    int day = (int)[t day];
    NSLog(@"%d",day);
    return (NSInteger)day;
    
}
- (NSInteger)setMinute
{
    NSDate *now=[NSDate date];
    NSCalendar *cal=[NSCalendar currentCalendar];
    unsigned int time=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    NSDateComponents *t=[cal components:time fromDate:now];
    
    int minute = (int)[t minute];
    NSLog(@"%d",minute);
    return (NSInteger)minute;
    
}


- (void)setLocation
{
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        [self.LocMan requestAlwaysAuthorization];
    }
    else
    {
        [self.LocMan startUpdatingLocation];
    }
    
//    [FPLocation shareInstance].locationID = 292;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationBtn setTitle:@"定位ing"];
    }
    else if (status == kCLAuthorizationStatusAuthorizedAlways ||
             status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        
        [self.LocMan startUpdatingLocation];
        
        
    }
    else
    {
        [self.locationBtn setTitle:@"地球"];
    }
    
    
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.LocMan stopUpdatingLocation];
    CLLocation *loca = [locations lastObject];
    [FPLocation shareInstance].FPlatitude = loca.coordinate.latitude;
    [FPLocation shareInstance].FPlongitude = loca.coordinate.longitude;
    NSLog(@"%f, %f speed = %f", loca.coordinate.latitude , loca.coordinate.longitude, loca.speed);
    NSString *locaUrl = [NSString stringWithFormat:kLocation,[FPLocation shareInstance].FPlatitude , [FPLocation shareInstance].FPlongitude];
  //  NSLog(@"==========%@",locaUrl);
    if (self.isLocation == YES)
    {
        return;
    }
    self.HUD2 = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.view bringSubviewToFront:_HUD2];
    
    if ([[FPNetWork shareInstance] rechability]) {
        self.HUD2.labelText = @"正在加载";
        [self SystemAnanysis:locaUrl];
    }
    else
    {
        self.HUD2.labelText = @"请检查网络";
    }
    _isLocation = YES;
    
}


- (void)setUrl
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.view bringSubviewToFront:_HUD];
    self.tableView.userInteractionEnabled = NO;
    if ([[FPNetWork shareInstance] rechability]) {
        self.HUD.labelText = @"正在加载";
        [self setTopViewUrl];
        [self setTodayHot];
    }
    else
    {
        self.HUD.labelText = @"请检查网络";
    }
    
    
}
- (void)setTopViewUrl
{
   
    NSString *str = [NSString stringWithFormat:kmainTopUrl,[FPLocation shareInstance].locationID];
    [self SystemAnanysis:str];
}

- (void)setTodayHot
{
    [self SystemAnanysis:kTodayHot];
}
- (void)AFNetWorking:(NSString *)str
{
    [LORequestManger GET:str success:^(id response) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
    
    
}
- (void)SystemAnanysis:(NSString *)str
{
    //NSLog(@"%@",str);
    NSURL * url = [NSURL URLWithString:str];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:60.0];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
      //  NSLog(@"%@",data);
        if (!data ) {
            self.HUD2.labelText = @"网络错误";
            self.HUD.labelText = @"网络错误";
            return ;
        }
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        if ([str isEqualToString:[NSString stringWithFormat:kLocation,[FPLocation shareInstance].FPlatitude , [FPLocation shareInstance].FPlongitude]])
        {
           // NSLog(@"%@",dic);
            NSString *str = dic[@"name"];
           // NSLog(@"%@",str);
           [FPLocation shareInstance].locationID = dic[@"cityId"];
            [self showAlert:[NSString stringWithFormat:@"当前所在城市%@",str]];
            [FPLocation shareInstance].cityLocal = str;
            [self.locationBtn setTitle:[NSString stringWithFormat:@"%@△",str]];
            [self.HUD2 hide:YES afterDelay:2];
            
            return;

        }
        
        
        
        if ([str isEqualToString:[NSString stringWithFormat:kmainTopUrl,[FPLocation shareInstance].locationID]]) {
            self.topModelArr = [NSMutableArray array];
            self.topModelArr = [FPmainTopViewModel setTopUrlDic:dic ];
            self.FindCinemaModel = [FPFindCinemaModel FindCinemaSetValueWithDic:dic];
            [self setTopImage];
            [self.HUD hide:YES afterDelay:2];


        }
        else
        {
            self.todayHotModelArr = [NSMutableArray array];
            NSArray *array = [dic objectForKey:@"hotPoints"];
            for (NSDictionary *smallDic in array) {
                FPTodayHotModel *model = [FPTodayHotModel TodayHotModelWithDic:smallDic];
               
                [self.todayHotModelArr addObject:model];
                
            }
            
            NSDictionary  *hotMovicDic = [dic objectForKey:@"hotMovie"];
            self.todayMovieModel = [FPTodayMovieModel TodayMovieWithDic:hotMovicDic];
//            NSLog(@"%@",_topModelArr);
//            [self.HUD hide:YES afterDelay:2];

            self.tableView.userInteractionEnabled = YES;


        }
    }];
    
}
- (void)setTopImage
{
    self.topImageArr = [NSMutableArray array];
    
    for (FPmainTopViewModel *model  in _topModelArr) {
//        NSLog(@"%@",model.imgstr);
        NSURL *url = [NSURL URLWithString:model.imgstr];
        [self.topImageArr addObject:url];
    }
//    NSLog(@"%@",_topImageArr);
    [self.tableView reloadData];
}
- (void)setNavigationView
{
//    self.navigationItem.title = @"首页";
    
    UILabel *label = [[UILabel alloc]init];
    label.height = kImageW(30);
    label.font = [UIFont systemFontOfSize:20];
    label.textColor = [UIColor whiteColor];
    label.text = @"首页";
    self.navigationItem.titleView = label;
    
    self.locationBtn = [[UIBarButtonItem alloc]initWithTitle:@"定位▽" style:UIBarButtonItemStylePlain target:self action:@selector(LocationBtn:)];
    self.locationBtn.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = _locationBtn;
    
    
    UIBarButtonItem *search = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"erwei"] style:UIBarButtonItemStylePlain target:self action:@selector(search)];
    search.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = search;
    
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth , kScreenHeight - 64)];
    self.imageQR = [[UIImageView alloc]initWithFrame:CGRectMake(kImageW(50), kImageH(200), kScreenWidth - kImageW(100), kImageH(250))];
    _imageQR.image = [UIImage imageNamed:@"QRCCCC－2（被拖移）.tiff"];
    [self.backView addSubview:_imageQR];
    [self.view addSubview:_backView];
   // UIImageView *backClear = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"QRCCCC－2（被拖移）.tiff"]];
    [self startQRAnmiation];
//    backClear.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:backClear];
//    _backView.backgroundColor = [UIColor redColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self hideNavigationBlackLine];
   //[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
}

- (void)startQRAnmiation
{
    NSMutableArray *imageArr = [NSMutableArray array];
    for (int i = 2; i < 6; i++) {
        NSString *str = [NSString stringWithFormat:@"QRCCCC－%d（被拖移）.tiff", i];
        UIImage *image = [UIImage imageNamed:str];
        [imageArr addObject:image];
    }
    _imageQR.animationImages = imageArr;
    _imageQR.animationRepeatCount = INT_MAX;
    _imageQR.animationDuration = 0.1 *imageArr.count;
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0,0, kScreenWidth, 64)];
    topView.backgroundColor = [UIColor colorWithRed:0.113 green:0.844 blue:1.000 alpha:1.000];
    [_backView addSubview:topView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(kImageH(5), kImageH(25), kImageW(100), kImageH(30));
    [button addTarget:self action:@selector(returnMain) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    [topView addSubview:button];
    
    UIButton *FlashLight = [UIButton buttonWithType:UIButtonTypeSystem];
    FlashLight.frame = CGRectMake(kScreenWidth - kImageW(50), kImageH(25), kImageW(40), kImageW(40));
    [FlashLight setImage:[UIImage imageNamed:@"light"] forState:UIControlStateNormal];
    [FlashLight addTarget:self action:@selector(flashLight:) forControlEvents:UIControlEventTouchUpInside];
    [FlashLight setTintColor:[UIColor whiteColor]];
    [topView addSubview:FlashLight];
    
    
}
- (void)setQRAnimation
{
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:4];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationRepeatCount:50];
    self.QRLine = [[UIView alloc]initWithFrame:CGRectMake(kImageW(15), kImageH(5), _imageQR.width - kImageW(30), kImageH(2))];
    [_imageQR addSubview:_QRLine];
    _QRLine.backgroundColor = [UIColor greenColor];
    [_QRLine setFrame:CGRectMake(kImageW(15),  _imageQR.height - kImageH(10), _imageQR.width - kImageW(30), kImageH(2))];
     [UIView commitAnimations];
}
- (void)flashLight:(UIButton *)btn
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (self.isFlashLight == NO) {
        
        [btn setImage:[UIImage imageNamed:@"lighton"] forState:UIControlStateNormal];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            if (open)
            {
                [device setTorchMode:AVCaptureTorchModeOn];
            }
            
            [device unlockForConfiguration];
        }
        
    }
    else
    {
        [btn setImage:[UIImage imageNamed:@"light"] forState:UIControlStateNormal];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            if (open)
            {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            
            [device unlockForConfiguration];
        }

        
        
        
    }
    _isFlashLight = !_isFlashLight;
    
}
- (void)returnMain
{
    NSLog(@"return");
    [_imageQR stopAnimating];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    self.backView.hidden = YES;
    _QRLine.y = kImageH(5);
    [_QRLine.layer removeAllAnimations];
    _QRLine.hidden = YES;
    [self.previewLayer removeFromSuperlayer];
}
/**
 *  隐藏Navigation下面的黑线
 */
- (void)hideNavigationBlackLine
{
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2=imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        imageView2.hidden=YES;
                    }
                }
            }
        }
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y < kImageH(50))
    {
        self.tableView.bounces = NO;

    }
    else
    {
        self.tableView.bounces = YES;

    }
   // NSLog(@"%f",scrollView.contentOffset.y);
    UIColor *color = [UIColor colorWithRed:0.180 green:0.596 blue:1.000 alpha:1.000];
    CGFloat offsetY = scrollView.contentOffset.y;
    self.statusBarView.frame =CGRectMake(0, 0, kScreenWidth  , 20);
    if (offsetY > 0) {
        CGFloat alpha = 1 - (44 - offsetY) / 44;
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:alpha];
       // [[UINavigationBar appearance]setBarTintColor:[color colorWithAlphaComponent:alpha]];

        _statusBarView.backgroundColor = [color colorWithAlphaComponent:alpha];
        
        [self setNeedsStatusBarAppearanceUpdate];
        [self.view addSubview:_statusBarView];
        
        
    }
    else {
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:0];

        _statusBarView.backgroundColor = [color colorWithAlphaComponent:0];
        [self setNeedsStatusBarAppearanceUpdate];
        
        [self.view addSubview:_statusBarView];
    }
   
}
- (void)LocationBtn:(UIBarButtonItem *)btn
{
    self.LocMan.delegate = self;

    [self setLocation];
    
    
    
}
- (void)search
{
    self.isScanf = NO;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    NSError *error = nil;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error) {
        [self showAlert:@"没有摄像头设备"];
        return;
    }
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    
    AVCaptureSession *session = [[AVCaptureSession alloc]init];
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    [session addInput:input];
    [session addOutput:output];
    
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    
    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    [preview setFrame:self.view.bounds];
    _backView.hidden = NO;
    [self.view.layer insertSublayer:preview atIndex:0];
    [self.view sendSubviewToBack:self.tableView];
    [_imageQR startAnimating];
    [self setQRAnimation];
    self.previewLayer = preview;
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [session startRunning];
    
}


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [self.session stopRunning];
    
    [self.previewLayer removeFromSuperlayer];
    
   
    if (metadataObjects.count > 0 && _isScanf == NO) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        NSLog(@"%@",obj.stringValue);
        [self turnWebViewstr:obj.stringValue];
//        FPCommWebView *webV = [[FPCommWebView alloc]init];
//        [webV setUrlstr:obj.stringValue];
////        [self.navigationController pushViewController:webV animated:YES];
//        
//        [self.view addSubview:webV];
       
        
        [self showAlert:obj.stringValue];
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        [_imageQR stopAnimating];
        [_QRLine.layer removeAllAnimations];
       
        self.isScanf = YES;
    }
    self.backView.hidden = YES;
    
}
- (void)turnWebViewstr:(NSString *)str
{
    UIViewController *webC = [[UIViewController alloc]init];
    UIWebView *webView = [[UIWebView alloc]init];
//    webView.delegate = self;
    
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    [webView loadRequest:request];
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth| UIViewAutoresizingFlexibleHeight;
    webView.scalesPageToFit = YES;
    [webC.view addSubview:webView];
    [self.navigationController pushViewController:webC animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }
    if (section == 2) {
        return 1;
    }
    return 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
/**
 *  给第三方设置图片
 *
 *  @param carousel <#carousel description#>
 *  @param index    <#index description#>
 *  @param view     <#view description#>
 *
 *  @return <#return value description#>
 */
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kImageW(150), kImageH(230))];
    [((UIImageView *)view) sd_setImageWithURL:[_topImageArr objectAtIndex:index] placeholderImage:[UIImage imageNamed:@"2.jpg"]];
    
    return view;
}

/**
 *  当图片改变和显示的时候自动调用的方法
 *
 *  @param carousel
 */
- (void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel
{
  
    //((FPVisualEffectView *)[self.view viewWithTag:100]).image = ((UIImageView *)carousel.currentItemView).image;
   [((FPVisualEffectView *)[self.view viewWithTag:100]) sd_setImageWithURL:[_topImageArr objectAtIndex:carousel.currentItemIndex]];
   // NSLog(@"%@",_topModelArr);
    FPmainTopViewModel *model = [_topModelArr objectAtIndex:carousel.currentItemIndex];
    ((UILabel *)[self.view viewWithTag:101]).text = model.titleCn;
    
    ((UILabel *)[self.view viewWithTag:102]).text = model.actorWord;
    
    
}
/**
 *  根据下标点击图片触发的方法
 *
 *  @param carousel <#carousel description#>
 *  @param index    <#index description#>
 */
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"%ld",index);
    FPMovieDetailViewController *movieDetailVC = [[FPMovieDetailViewController alloc]init];
    movieDetailVC.viewModel = _topModelArr[index];
    [self.navigationController pushViewController:movieDetailVC animated:YES];
    
    
    
}
- (void)BtnType
{
    ((iCarousel *)[self.view viewWithTag:103]).type =  arc4random()%11;
    
}
- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
    return YES;
}
- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return _topModelArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        
       
        self.imageDic = [NSMutableDictionary dictionary];
        
        
        static NSString *ID = @"cell";
        [tableView registerClass:[FPMainTopTableViewCell class] forCellReuseIdentifier:ID];
       // NSLog(@"%@",_topImageArr);
        FPMainTopTableViewCell *cell = [[FPMainTopTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID array:self.topImageArr index:_imageIndex ];
        cell.visual.tag = 100;
        FPmainTopViewModel *model = [_topModelArr objectAtIndex:indexPath.row];
        cell.Titlelabel.text = model.titleCn;
        cell.Titlelabel.tag = 101;
        cell.wordlbl.text = model.actorWord;
        cell.wordlbl.tag = 102;
        cell.carousel.tag = 103;
        //设置代理
        cell.carousel.delegate = self;
        cell.carousel.dataSource = self;
        [cell.ImageTypeBtn addTarget:self action:@selector(BtnType) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        
        
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    if (indexPath.section == 0 && indexPath.row == 1)
    {
        static NSString *ID2 = @"cell2";
        [tableView registerClass:[FPThreeBtnTableViewCell class] forCellReuseIdentifier:ID2];
        FPThreeBtnTableViewCell *cell  = [[FPThreeBtnTableViewCell alloc]init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ThreeBtn:)];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ThreeBtn:)];
        UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ThreeBtn:)];

        cell.hotMovieView.tag = 105;
        cell.willMovieView.tag = 106;
        cell.findCinemaView.tag = 107;
        [cell.hotMovieView addGestureRecognizer:tap1];
        [cell.willMovieView addGestureRecognizer:tap2];
        [cell.findCinemaView addGestureRecognizer:tap3];
        
        
        cell.hotMovielbl.text = [NSString stringWithFormat:@"%d", self.FindCinemaModel.totalHotMovie ];
        cell.willMovielbl.text = [NSString stringWithFormat:@"%d", self.FindCinemaModel.totalComingMovie];
        cell.findCinemalbl.text = [NSString stringWithFormat:@"%d", self.FindCinemaModel.totalCinemaCount];
        return cell;
        
    }
    if (indexPath.section == 1) {
       return  [self setHotToday:tableView index:indexPath];
    }
    else
    {
        static NSString *IDx = @"cellx";
        [tableView registerClass:[FPGoodMovieTableViewCell class] forCellReuseIdentifier:IDx];
        FPGoodMovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDx forIndexPath:indexPath];
        NSURL *urltop = [NSURL URLWithString:_todayMovieModel.topCover];
        NSURL *urlSmall = [NSURL URLWithString:_todayMovieModel.image];
        [cell.BigImage sd_setImageWithURL:urltop placeholderImage:[UIImage imageNamed:@"0.jpg"]];
        cell.titlelbl.text = _todayMovieModel.title;
        cell.messlbl.text = _todayMovieModel.desc;
        cell.movieTielbl.text = _todayMovieModel.titleCn;
        cell.authorlbl.text = _todayMovieModel.titleEn;
        [cell.smallImage sd_setImageWithURL:urlSmall placeholderImage:[UIImage imageNamed:@"2.jpg"]];
        return cell;
    }
}
- (void)ThreeBtn:(UIGestureRecognizer *)sender
{
    
    NSLog(@"%ld",sender.view.tag);
    if (sender.view.tag == 105) {
        FPRootViewController *fpmovieVC = [[FPRootViewController alloc]init];
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
      
        [self.navigationController pushViewController:fpmovieVC animated:YES];
    }
    else if (self.view.tag == 106)
    {
        FPRootViewController *fpmovieeeeVC = [[FPRootViewController alloc]init];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        [self.navigationController pushViewController:fpmovieeeeVC animated:YES];
    }
    else
    {
        FPCinemaViewController *cinemaVC = [[FPCinemaViewController alloc]init];
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        [self.navigationController pushViewController:cinemaVC animated:YES];
    }
}
- (UITableViewCell *)setHotToday:(UITableView *)tableview index:(NSIndexPath *)indexPath
{
    static NSString *ID3 = @"cell3";
    [tableview registerClass:[FPTodayHotTableViewCell class] forCellReuseIdentifier:ID3];
    FPTodayHotTableViewCell *cell = [[FPTodayHotTableViewCell alloc]init];
    
    FPTodayHotModel *model = _todayHotModelArr[indexPath.row];
   
    
    NSURL *url = [NSURL URLWithString:model.img];
    [cell.hotImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"45545363.jpg"]];
    [cell cellForHeight:model.title];
    cell.messlbl.text = model.desc;
//    NSLog(@"%@",model.img);
    
//    NSLog(@"%@", str2);
    NSInteger urlHour = [self setTimeString:model.img From:36 To:2];
    NSInteger urlDay = [self setTimeString:model.img From:33 To:2];
    NSInteger urlMinute = [self setTimeString:model.img From:38 To:2];
    NSLog(@"%ld", urlMinute);
    NSLog(@"%ld", urlDay);
    NSLog(@"%ld", urlHour);
    NSInteger intervalDay = [self setDay] - urlDay;
    NSInteger intervalHour = [self setHour] -  urlHour  ;
    NSInteger intervalMinute = [self setMinute] - urlMinute;
   cell.timelbl.text = [self setTimeDay:intervalDay Hour:intervalHour Minute:intervalMinute];
    
    return  cell;
    
    
}
- (NSString *)setTimeDay:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute
{
    //NSLog(@"%ld    %ld      %ld",day,hour,minute);
    if (day > 0) {
        if (hour > 0)
        {
            return @"一天前";
        }
        else if(minute < 0)
        {
            return [NSString stringWithFormat:@"%ld小时%ld分钟前",hour + 23,minute + 60 ];
        }
        else
        {
            return [NSString stringWithFormat:@"%ld小时前",hour + 24 ];
        }
    }
    else
    {
        if (hour >= 0) {
            if (minute > 0 && hour == 0) {
                return [NSString stringWithFormat:@"%ld分钟前",minute];

            }
            else
            {
                return [NSString stringWithFormat:@"%ld小时前",hour  ];
            }
        }
        else
        {
            NSLog(@"DDDDD%ldHHHHHH%ldMMMMMMM%ld",day,hour,minute);

            NSLog(@"时间错误!!!!!!!!!!");
            return nil;
        }
    }
}

- (NSInteger)setTimeString:(NSString *)str From:(NSInteger)from To:(NSInteger)to
{
    NSString *str1 = [str substringFromIndex:from];
    NSString *str2 = [str1 substringToIndex:to];
    
    return [str2 integerValue];
    
}
- (UITableViewCell *)setThreeImage:(UITableView *)tableView
{
    static NSString *ID4  = @"cell4";
    [tableView registerClass:[FPThreeImageTableViewCell class] forCellReuseIdentifier:ID4];
    FPThreeImageTableViewCell *cell = [[FPThreeImageTableViewCell alloc]init];
    cell.image1.image = [UIImage imageNamed:@"4.jpg"];
    cell.image2.image = [UIImage imageNamed:@"296b467c57933f291a29e2c2255af022.jpg"];
    cell.image3.image = [UIImage imageNamed:@"45545363.jpg"];
    
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        FPTodayHotView *todHotV = [[FPTodayHotView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(50))];
        [todHotV.moreBtn addTarget:self action:@selector(more) forControlEvents:UIControlEventTouchUpInside];
        
        return todHotV;
    }
    if (section == 2) {
        FPEveryMovieHeadView *eveMovieV = [[FPEveryMovieHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(50))];
        return eveMovieV;
    }
    else
    {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return kImageH(40);
    }    else
    {
        
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1 || section == 2) {
        return kImageH(40);
    }
    else
    {
        
        return 0;
    }
    
}
- (void)more
{
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    FPFootView *footView = [[FPFootView alloc]init];
    [footView.newsBtn addTarget:self action:@selector(FourBtn:) forControlEvents:UIControlEventTouchUpInside];
    footView.newsBtn.tag = 110;
    [footView.prevueBtn addTarget:self action:@selector(FourBtn:) forControlEvents:UIControlEventTouchUpInside];
    footView.prevueBtn.tag = 111;

    [footView.topBtn addTarget:self action:@selector(FourBtn:) forControlEvents:UIControlEventTouchUpInside];
    footView.topBtn.tag = 112;

    [footView.discussBtn addTarget:self action:@selector(FourBtn:) forControlEvents:UIControlEventTouchUpInside];
    footView.discussBtn.tag = 113;


    footView.backgroundColor = [UIColor whiteColor];
    return footView;
}
- (void)FourBtn:(UIButton *)btn
{
    if (btn.tag == 110) {
        FPNewsViewController *newVC = [[FPNewsViewController alloc]init];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        self.automaticallyAdjustsScrollViewInsets = YES;

       
        [self.navigationController pushViewController:newVC animated:YES];
    }
    else if (btn.tag == 111)
    {
        FPPrevueViewController *prevueVC = [[FPPrevueViewController alloc]init];
       
        [self.navigationController pushViewController:prevueVC animated:YES];
    }
    else if (btn.tag == 112)
    {
        FPTopViewController *topVC = [[FPTopViewController alloc]init];
       
        [self.navigationController pushViewController:topVC animated:YES];
    }
    else
    {
        FPFilmcriticViewController *filmVC = [[FPFilmcriticViewController alloc]init];
        [self.navigationController pushViewController:filmVC animated:YES];
    }
    
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 1) {
        FPTodayHotModel *model = _todayHotModelArr[indexPath.row];
        FPWebViewController *webVC = [[FPWebViewController alloc]init];
        webVC.stringURl = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/Detail.api?newsId=%@",model.todayHotid];
        [self.navigationController pushViewController:webVC animated:YES];
    }
    if (indexPath.section == 2) {
        
    }
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return kImageH(500);
    }
    
    if (indexPath.section == 2) {
        return kImageH(250);
    }
    else
    {
        return kImageH(90);
        
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

    self.automaticallyAdjustsScrollViewInsets = NO;
  //  [self.view setBounds:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
   [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    _statusBarView.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
}
- (void)viewDidDisappear:(BOOL)animated
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
}
#pragma  mark ****懒加载*****
- (CLLocationManager *)LocMan
{
    if (!_LocMan) {
        _LocMan = [[CLLocationManager alloc]init];
    }
    
    return _LocMan;
}
- (UIView *)statusBarView
{
    if (!_statusBarView) {
        _statusBarView = [[UIView alloc]init];
    }
    return _statusBarView;
}
- (UITableView *)tableView
{
    if (!_tableView ) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44) style:UITableViewStylePlain];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
//根据NSTimer来给AlertView定时, 让显示完后消失
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
    [theTimer invalidate];
}

//弹出AlertView
- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.2f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
